import { makeAutoObservable } from 'mobx';
import * as api from './api';

export default class DictItemStore {
  pageSize = PGSIZE;
  pageNo = 1;
  keyword = undefined;
  total = 0;
  loading = false;
  data = []; // table 数据
  // treeData = {}; // itemId = {dictItem}
  // treeSelectedId = ''; // selected itemId

  constructor(rootStore) {
    makeAutoObservable(this);
  }

  api() {
    return api;
  }

  /**
   * 发起获取列表
   */
  * fetch(dictId) {
    this.loading = true;
    try {
      this.total = yield api.countDictItem(dictId, { keyword: this.keyword });
      this.data = yield api.searchDictItem(dictId, { keyword: this.keyword, page: (this.pageNo - 1), size: this.pageSize, sort: 'itemId' });
    } finally {
      this.loading = false;
    }
  }

  reset(dictId) {
    this.keyword = '';
    this.pageNo = 1;
    this.fetch(dictId);
  }

  setSizeList(dictId, val) {
    if (val === this.pageSize) return;
    this.pageSize = val;
    this.fetch(dictId);
  }

  setPageNo(dictId, val) {
    if (val === this.pageNo) return;
    this.pageNo = val;
    this.fetch(dictId);
  }

  setKeyword(dictId, val) {
    if (val === this.keyword) return;
    this.keyword = val;
    if (val === '') this.fetch(dictId);
  }

  /**
   * 计算表格中的索引
   * @param {number} i 表格说因
   * @returns 数据索引
   */
  idx(i) {
    return (this.pageNo - 1) * this.pageSize + i + 1;
  }

  /**
   * 创建字典
   * @param {*} dictItem 待添加的字典
   * @returns 创建后的字典
   */
  create(dictItem) {
    return api.createDictItem(dictItem).then((d) => {
      this.reset(dictItem.dictId);
      return d;
    });
  }

  /**
   * 创建字典
   * @param {*} dictItem 待添加的字典
   * @returns 创建后的字典
   */
  update(dictItem) {
    return api.updateDictItem(dictItem).then((d) => {
      this.fetch(dictItem.dictId);
      // // 修改本地treeData
      // this.treeData[d.itemId] = d;
      return d;
    });
  }

  delete(dictId, itemId) {
    return api.deleteDictItem(dictId, itemId).then((d) => {
      this.fetch(dictId);
      return d;
    });
  }

  getDict(dictId) {
    return api.getDict(dictId);
  }

}

